package com.myown.util;

import com.octo.captcha.service.CaptchaServiceException;
import com.octo.captcha.service.image.ImageCaptchaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Locale;

/**
 * 验证码工具类 <p>
 * @author lincky
 * @version v1.0.0
 */
@Component
public class JCaptchaInfo {

    // JCaptcha spring注入服务对象
    @Autowired
    private ImageCaptchaService imageCaptchaService;

    public void setImageCaptchaService(ImageCaptchaService imageCaptchaService) {
        this.imageCaptchaService = imageCaptchaService;
    }

    public ImageCaptchaService getImageCaptchaService() {
        return imageCaptchaService;
    }

    /**
     * 获取验证码图像流 <p>
     * @param captchaId 验证码id
     * @param locale request属性locale
     * @return 验证码图像字节流
     * @throws IOException io异常
     */
    public ByteArrayOutputStream getJpegOutputStream(String captchaId, Locale locale) throws IOException {
        ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
        BufferedImage challenge = imageCaptchaService.
                getImageChallengeForID(captchaId, locale);
        ImageIO.write(challenge, "jpeg", jpegOutputStream);
        return jpegOutputStream;
    }

    /**
     * 验证码与sessionId绑定，验证一次撤销sessionId信息 <p>
     * @param sessionId session的id号
     * @param code 验证码
     * @return <tt>true</tt> - 验证码正确
     */
    public boolean isCorrect(String sessionId, String code) {
        boolean isCorrect = false;
        try {
            isCorrect = imageCaptchaService.validateResponseForID(sessionId, code);
        } catch (CaptchaServiceException ignored) {
        }
        return isCorrect;
    }
}
